

#include "client.h"

YatunClient::YatunClient(ConfigParser *in) {
    Config = in;
}

YatunClient::~YatunClient() {
    delete Tun;
    delete SessionName;
}

int SetConf(struct YatunClientConf &in) {
//    int inPort = YATUN_DEFAULT_PORT;
    char *RemoteAddr;
    char *LocalModule;
    c_Plug_IO *IOLocal;
    c_Plug_IO *IORemote;
    c_Plug_IO *IOTmp;
    struct sockaddr_in localaddr;
    struct YatunTunnelConf TunnelConf;
    int UseMServer = 0;
        
    SessionName = in.SessionName;
    mServerAddress = in.mServerAddress;
    mServerPort = in.mServerPort;
    UseMServer = in.UseMServer;

//    if (Config->GetSection ("Main")) {
//        fprintf (stderr, "Section [Main] does not exist in config file!!! \n", SessionName);
///        exit (-1);
//    }

//    Config->GetPropertyByType ("port", &inPort, T_INT);
//    Config->GetPropertyByType ("UseMServer", &UseMServer, T_BOOL);

    if (Config->GetSection (SessionName)) {
        fprintf (stderr, "Section [%s] does not exist in config file!!! \n", SessionName);
        exit (-1);
    }
    
    LocalModule = new char[20];
    if (Config->GetPropertyByType ("LocalModule", LocalModule, T_STRING)) { 
	printf ("No local module specified \n"); 
	delete LocalModule; 
	return -1;
    }

    
    if(strncmp(LocalModule, "tun", 3) == 0) {
        char *TunName = new char[20];
	if (Config->GetPropertyByType ("TunName", TunName, T_STRING)) { 
	
	    IOLocal = new IOTun;
	} else {
	    IOLocal = new IOTun(TunName);
	    delete TunName;
	}
	
    } else {
	printf ("Unknown local module \n");
	return -2;
    }
    ret = IOLocal->Open();

    if(UseMServer) {
	RemoteAddr = new char[30];    
	if (Config->GetPropertyByType ("RemoteAddr", RemoteAddr, T_STRING)) { 
	    printf ("No Up script specified \n"); 
	    delete RemoteAddr; 
	    return -1;
	}
        
	localaddr.sin_family = AF_INET;
//	localaddr.sin_port = htons (in.Port);
	localaddr.sin_addr.s_addr = INADDR_ANY;

	IOTmp = new IO_TCP (&localaddr);
	IOTmp->Open();

    } else {
//	mServerClient *mServer = new mServerClient();
	localaddr.sin_family = AF_INET;
	localaddr.sin_port = htons (mServerPort);
	localaddr.sin_addr.s_addr = inet_addr(mServerAddress);

	IOTmp = new IO_UDP (&localaddr);
//	mServer->NegotiateClient(IOTmp);
    }
    
    IORemote = Negotiate(IOTmp, TunnelConf);
    Tunnel = new YatunTunnel(IOLocal, IORemote);
    
    Tunnel->SetConf(TunnelConf);
    
}

c_Plug_IO* YatunClient::NegotiateServer(c_Plug_IO *IORemote,struct YatunTunnelConf &TunnelConf) {

}

int YatunClient::NegotiateMServer(c_Plug_IO *IORemote) {

}